package com.thinkfit.jy.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.common.lib.bean.RecordDetailBean;
import com.common.lib.bean.RecordInfoBean;
import com.common.lib.bean.RecordItemListBean;
import com.common.lib.bean.UserBean;
import com.common.lib.constant.Constants;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.thinkfit.jy.R;
import com.thinkfit.jy.contract.SportReportContract;
import com.thinkfit.jy.presenter.SoprtReportPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.LoadViewUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.ThemeUtils;

import java.util.ArrayList;
import java.util.List;

public class SportReportActivity extends MainActivity implements SportReportContract.View{

    WebView web;
    ConstraintLayout clMain,clSportInfo;
    int mRid;

    TextView tvDistance,tvSportType,tvSportTime,tvSportkcal,tvSportAvgSpeed,tvSportAvgPace,tvSportAvgStride,tvSportAvgStrideUnit
            , tvUserName,tvMaxSpeed,tvAvgSpeed,tvMaxSpm,tvAvgSpm,tvMaxSpmTip,tvLc2Title,tvAvgSpmTip;
    ImageView ivUserHead,ivQr;
    LineChart lc1,lc2;

    protected int getLayoutId() {
        return R.layout.activity_sport_report;
    }

    @NonNull
    @Override
    protected SportReportContract.Presenter onCreatePresenter() {
        return new SoprtReportPresenter(this);
    }

    @Override
    public void init() {
        mRid = getIntent().getIntExtra(Constants.BUNDLE_EXTRA,0);
        setViewsOnClickListener(R.id.ll_sport_back);
        clMain = findViewById(R.id.cl_main);
        clSportInfo = findViewById(R.id.cl_sport_info);
        tvDistance = findViewById(R.id.tv_distance);
        tvSportType = findViewById(R.id.tv_sport_type);
        tvSportTime = findViewById(R.id.tv_sport_time);
        tvSportkcal = findViewById(R.id.tv_sport_kcal);
        tvSportAvgSpeed = findViewById(R.id.tv_sport_avg_speed);
        tvSportAvgPace = findViewById(R.id.tv_sport_avg_pace);
        tvSportAvgStride = findViewById(R.id.tv_sport_avg_stride);
        tvSportAvgStrideUnit = findViewById(R.id.tv_sport_avg_stride_unit);
        tvMaxSpeed = findViewById(R.id.tv_max_speed);
        tvAvgSpeed = findViewById(R.id.tv_avg_speed);
        tvMaxSpm = findViewById(R.id.tv_max_spm);
        tvAvgSpm = findViewById(R.id.tv_avg_spm);
        tvMaxSpmTip = findViewById(R.id.tv_max_spm_tip);
        tvLc2Title = findViewById(R.id.tv_lc2_title);
        tvAvgSpmTip = findViewById(R.id.tv_avg_spm_tip);

        ivUserHead = findViewById(R.id.iv_user_head);
        ivQr = findViewById(R.id.iv_qr);
        tvUserName = findViewById(R.id.tv_user_name);
//        tvUserTime = findViewById(R.id.tv_user_time);
        lc1 = findViewById(R.id.lc_1);
        lc2 = findViewById(R.id.lc_2);

        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if(myInfo != null){
            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
            tvUserName.setText(myInfo.getNickname());
        }

        if(DeviceTypeUtils.getDeviceType() == 1 || DeviceTypeUtils.getDeviceType() == 6){
            tvSportAvgStrideUnit.setText(getString(R.string.app_rpm));
            tvMaxSpmTip.setText(getString(R.string.app_best_rpm));
            tvLc2Title.setText(getString(R.string.app_speed_rate_rpm));
            tvAvgSpmTip.setText(getString(R.string.app_free_avg_cadence));
        }else {
            tvSportAvgStrideUnit.setText(getString(R.string.app_spm));
        }
//        web = findViewById(R.id.webView);
//        initWeb();
//        int language = DataManager.Companion.getInstance().getLanguage();
//        String url = "https://www.thinkfiter.com/zjcp/H5/index.html#/?rid="+mRid+"&langId="+language+"&unitnum=0&brandid=100&style=4";
//
//        web.loadUrl(url);
//        List<Entry> list=new ArrayList<>();
//        for (int i=0;i<2;i++){
//            list.add(new Entry(i, (float) (Math.random()*60)));
//        }
        initLine(lc1);
        initLine(lc2);
//        mRid = 224;
        ((SoprtReportPresenter) getPresenter()).recordDetail(mRid);//获取应用列表
    }

    public void initLine(LineChart lc){

//        LineDataSet lineDataSet=new LineDataSet(list,title);
//
//        lineDataSet.setColor(lineColor);
//        lineDataSet.setDrawCircles(false);//折线上的小圆点
//        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);//这里是圆滑曲线
//        lineDataSet.setHighLightColor(getColor(R.color.white));
//        lineDataSet.setValueTextColor(getColor(R.color.white));
//        lineDataSet.setValueTextSize(0);

        // 设置X轴可见范围的最大值
        lc.setVisibleXRangeMaximum(100);

        // 设置Y轴可见范围的最大值
        lc.setVisibleYRangeMaximum(100, YAxis.AxisDependency.LEFT);

        lc.getXAxis().setDrawGridLines(false);
        lc.getXAxis().setDrawAxisLine(true);
        //是否绘制右侧轴线
        lc.getAxisRight().setEnabled(false);
        lc.getAxisLeft().setDrawGridLines(false);
        lc.getAxisRight().setDrawGridLines(false);

        lc.getXAxis().setAxisMinimum(0f);
        lc.getAxisLeft().setAxisMinimum(0f);
        lc.getXAxis().setTextColor(getColor(R.color.white));
        lc.getAxisLeft().setTextColor(getColor(R.color.white));
        //设置x轴的位置
        lc.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

        Description description=new Description();
        description.setEnabled(false);
        lc.setDescription(description);


        //对legend的一些设置
        //得到legend对象
        Legend legend=lc.getLegend();
        legend.setEnabled(false);
        legend.setTextColor(Color.RED);

        LineData lineData = new LineData();
        lc.setData(lineData);
    }

    public void setLineData(LineChart lc,List<Entry> list,String title,int lineColor){
        LineDataSet lineDataSet=new LineDataSet(list,title);

        lineDataSet.setColor(lineColor);
        lineDataSet.setDrawCircles(false);//折线上的小圆点
        lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//这里是圆滑曲线
        lineDataSet.setHighLightColor(getColor(R.color.white));
        lineDataSet.setValueTextColor(getColor(R.color.white));
        lineDataSet.setValueTextSize(0);
        LineData lineData = new LineData(lineDataSet);
        lc.clearValues();
        lc.setData(lineData);
    }

    public void initWeb(){
        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        web.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                web.setVisibility(View.VISIBLE);
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        SportsStatusBarViewUtils.getInstance().isMain(false);
        ShowSpeedViewUtils.getInstance().goneLayout();
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        web.destroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_sport_back:
                finish();
                break;
        }
    }

    @Override
    public void resetInfo(SerialPortManager.CurrentInfo info) {

    }
    List<Entry> listSpeeds=new ArrayList<>();
    List<Entry> listRpm=new ArrayList<>();


    @Override
    public void recordDetailSuccess(RecordDetailBean bean) {
        LoadViewUtils.getInstance().goneLayout();
        RecordInfoBean record = bean.getRecordetal();
        long time = record.getEndtime() - record.getStarttime();
        tvSportTime.setText(getTime(Integer.valueOf(String.valueOf(time))));


        lineChar(bean.getItemlist());
//        List<Entry> list=new ArrayList<>();
//        for (int i=0;i<10;i++){
//            list.add(new Entry(i, (float) (Math.random()*60)));
//        }
//        setLineData(lc1,list,"速度",getColor(R.color.color_13B65E));
//        setLineData(lc2,list,"步频",getColor(R.color.color_FCBF24));
        tvDistance.setText(record.getDistance());
//        if(record.getType() == 1){
//            tvSportType.setText(getString(R.string.app_sport_center_video_course));
//        }else {
//            tvSportType.setText(getString(R.string.app_free_sport));
//        }
        tvSportType.setText(record.getModelname());

        String avgPace = null;
        try {
            float distance = Float.valueOf(record.getDistance());
            int sec = (int) (time /distance);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
            int hour = (int) (sec / 3600);
            int minute = (int) ((sec / 60) % 60);
            int second = (int) (sec % 60);
            if (hour > 0) {
                avgPace = BaseUtils.StaticParams.getNewText(hour) + ":"
                        + BaseUtils.StaticParams.getNewText(minute) + "'"
                        + BaseUtils.StaticParams.getNewText(second)+"''";
            } else {
                avgPace = BaseUtils.StaticParams.getNewText(minute) + "'"
                        + BaseUtils.StaticParams.getNewText(second)+"''";
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        tvSportAvgPace.setText(avgPace);

//        tvUserTime.setText(record.getDatetime());
        tvSportkcal.setText(record.getKcal());

//        tvSportAvgPace.setText();

        String shareUrl = "http://www.thinkfiter.com/zjxj/yyshare/#/?obj="+mRid+","+DataManager.Companion.getInstance().getLanguage()+
                ","+ (DataManager.Companion.getInstance().getUnit()? 1:0) +",100";
        createQRCOde(shareUrl);
    }

    public void lineChar(List<RecordItemListBean> itemlist){
        for (int i=0;i<itemlist.size();i++){
            if(itemlist.get(i).getSpeedlist() != null&&itemlist.get(i).getSpeedlist().size()>0){
                for (int y=0;y<itemlist.get(i).getSpeedlist().size();y++){
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   listSpeed : "+Float.valueOf(itemlist.get(i).getSpeedlist().get(y)));
                    listSpeeds.add(new Entry(y, Float.valueOf(itemlist.get(i).getSpeedlist().get(y))));
                }
                tvSportAvgSpeed.setText(itemlist.get(i).getAdv());
                tvMaxSpeed.setText(itemlist.get(i).getHeight());
                tvAvgSpeed.setText(itemlist.get(i).getAdv());
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   listSpeeds.size : "+listSpeeds.size());
                setLineData(lc1,listSpeeds,getString(R.string.app_speed_txt),getColor(R.color.color_FFB55B));
//                initLine(lc2,list,"步频",getColor(R.color.color_FCBF24));
            }else if(itemlist.get(i).getRpmlist() != null&&itemlist.get(i).getRpmlist().size()>0){
                for (int y=0;y<itemlist.get(i).getRpmlist().size();y++){
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   listRpm : "+Float.valueOf(itemlist.get(i).getRpmlist().get(y)));
                    listRpm.add(new Entry(y, Float.valueOf(itemlist.get(i).getRpmlist().get(y))));
                }
                tvMaxSpm.setText(itemlist.get(i).getHeight());
                tvAvgSpm.setText(itemlist.get(i).getAdv());
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   listRpm.size : "+listRpm.size());
                setLineData(lc2,listRpm,getString(R.string.app_step_rate),getColor(R.color.color_FF3B3B));
                tvSportAvgStride.setText(itemlist.get(i).getAdv());
            }
        }
//        Observable.create(new ObservableOnSubscribe<Object>() {
//            @Override
//            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
//
//            }
//        }).subscribe(new Observer<Object>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(Object o) {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
    }

    private void createQRCOde(String qrUrl){

        try {
            // 使用 MultiFormatWriter 生成 BitMatrix
            BitMatrix bitMatrix = new MultiFormatWriter().encode(qrUrl, BarcodeFormat.QR_CODE, dp2px(100), dp2px(100));

            // 使用 BarcodeEncoder 将 BitMatrix 转换为 Bitmap
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);

            Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(roundedBitmap);
            Paint paint = new Paint();
            paint.setAntiAlias(true);

            RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
            canvas.drawRoundRect(rect, dp2px(3), dp2px(3), paint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, 0, 0, paint);

            // 在 ImageView 中显示生成的二维码

            ivQr.setImageBitmap(roundedBitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getTime(int ss){
        String text;
        int hour = ss / 3600;
        int minute = (ss / 60) % 60;
        int second = ss % 60;
        if (hour > 0) {
            text = BaseUtils.StaticParams.getNewText(hour) + ":"
                    + BaseUtils.StaticParams.getNewText(minute) + ":"
                    + BaseUtils.StaticParams.getNewText(second);
        } else {
            text = BaseUtils.StaticParams.getNewText(minute) + ":"
                    + BaseUtils.StaticParams.getNewText(second);
        }

        return text;
    }

    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }

}
